package MathCore.Renders;

import MathCore.Expression;
import MathCore.Lexeme;
import MathCore.Operands.Variable;
import MathCore.Operators.ArOperator;
import MathCore.Render;
import MathCore.Symbol;
import javax.microedition.lcdui.Graphics;

/**
 *
 * @author Александр
 */
public class Atom extends Block
{
	private Lexeme lex = null;
	private int type = TYPE_OPERAND;

	public Atom(Lexeme lex)
	{
		this.lex = this.link = lex;
		width = Render.getFont().stringWidth(lex.toString());
		height = Render.getFont().getHeight();
		center = height/2;

		if(lex instanceof Symbol)
		{
			Symbol s = (Symbol) lex;
			if(s.getType() == Symbol.LEFT_BRACE || s.getType() == Symbol.LEFT_LIST) type = TYPE_OPEN_BRACKET;
			else if(s.getType() == Symbol.RIGHT_BRACE || s.getType() == Symbol.RIGHT_LIST) type = TYPE_CLOSE_BRACKET;
			else type = TYPE_STOPING_OPERATOR;
		}
		else if(lex instanceof ArOperator)
		{
			ArOperator o = (ArOperator) lex;
			if(o.getType() == o.ADDITION || o.getType() == o.SUBSTRACTION) type = TYPE_STOPING_OPERATOR;
			else if(o.getType() == o.PRODUCT) type = TYPE_NON_STOPING_OPERATOR;
			else if(o.getType() == o.DIVISION) type = TYPE_DIVISION;
			else if(o.getType() == o.POWER) type = TYPE_POWER;
		}
	}

	public void setChanged()
	{
		width = Render.getFont().stringWidth(lex.toString());
		height = Render.getFont().getHeight();
		center = height/2;

		((Stripe)parent).setChange();
	}

	public Lexeme lex(){ return lex; }

	public int width()
	{
		return width;
	}

	public int height()
	{
		return height;
	}

	public int center()
	{
		return center;
	}

	public void draw(Graphics g, int x, int y, int style)
	{
		saveCoordinates(x, y, style);

		// смещаем координаты, учитывая стили (сводим к LEFT|TOP)
		if(style(style, Block.BOTTOM))	y -= height();
		if(style(style, Block.RIGHT))	x -= width();
		if(style(style, Block.HCENTER))	x -= width()/2;
		if(style(style, Block.VCENTER)) y -= height() - center();

		// рисуем
		if(g == null) return;
		if(lex instanceof Variable) g.setColor(Render.variableColor);
		else g.setColor(Render.textColor);
		g.drawString(lex.toString(), x, y, Graphics.LEFT|Graphics.TOP);

		if(Render.activeBlock == this && Render.useCursor)
		{
			g.setColor(Render.linkColor);
			g.drawLine(x+width(), y, x+width(), y+height()-1);
			g.drawLine(x, y+height()-1, x+width(), y+height()-1);
		}
	}

	public void extract(Expression exp)
	{
		exp.add(lex.clone());
	}

	public String toString()
	{
		if(lex != null) return lex.toString();
		else return "<empty>";
	}

	public int type()
	{
		return type;
	}

	public void parse(){}

}
